from  flask import Flask,render_template,session,redirect,url_for,flash
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
import os
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, migrate
from flask_mail import Mail
from flask_mail import Message
from threading import Thread

class NameFrom(FlaskForm):
    name=StringField('What is your name?',validators=[DataRequired()])
    submit=SubmitField('Submit')

basedir = os.path.abspath(os.path.dirname(__file__))
app=Flask(__name__)

app.config['SECRET_KEY'] = '33483798'

app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = '2781363079@qq.com'
app.config['MAIL_PASSWORD'] = 'zvdxezgfuygfdhbj' 
app.config['FLASKY邮件前缀'] = '[Flasky]博客'
app.config['FLASKY邮件发送人'] = 'Flasky 管理员 <2781363079@qq.com>'
app.config['FLASKY管理员']='2781363079@qq.com'


bootstrap=Bootstrap(app)
moment=Moment(app) 
db = SQLAlchemy(app)
migrate=Migrate(app,db)
mail=Mail(app)

def send_async_email(app, msg):
     with app.app_context():
        mail.send(msg)

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['FLASKY邮件前缀'] + subject,
    sender=app.config['FLASKY邮件发送人'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    #mail.send(msg)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr
 
class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role',lazy='dynamic')
    def __repr__(self):
     return '<Role %r>' % self.name
     
class User(db.Model):
 __tablename__ = 'users'
 id = db.Column(db.Integer, primary_key=True)
 username = db.Column(db.String(64), unique=True, index=True)
 role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
 def __repr__(self):
     return '<User %r>' % self.username
@app.route('/',methods=['GET','POST'])
def index(): 
    #name=None
    nameform=NameFrom()
    if nameform.validate_on_submit():
        #name=nameform.name.data
        #nameform.name.data =''
        #old_name = session.get('name')
        #print(old_name, nameform.name.data)
        #if old_name is not None and old_name != nameform.name.data:
        #  flash('名字已更改!','success')
        user = User.query.filter_by(username=nameform.name.data).first()
        if user is None:
          user = User(username=nameform.name.data)
          db.session.add(user)
          db.session.commit()
          session['known'] = False
          flash('很高兴见到你','danger')
          if app.config['FLASKY管理员']:
            send_email(app.config['FLASKY管理员'], '新用户',
            'mail/new_user', user=user)
        else:
          session['known'] = True
          flash('很荣幸见到你','success')
          session['name']=nameform.name.data
          nameform.name.data=''
        return redirect(url_for('index'))
    return render_template('index.html',current_time=datetime.utcnow(),name=session.get('name'),nameform=nameform)
@app.route('/user/<name>')
def user(name):
    return  render_template('user.html',name=name)
@app.errorhandler(404)
def page_not_found(e): 
    return render_template('404.html'),404 
@app.shell_context_processor
def make_shell_context():
 return dict(db=db, User=User, Role=Role)

 
                                     